<template>
  <div class="app-container" ref="content">
    <div style="align-content: center">
      <el-form inline>
        <el-form-item label="人员">
          <el-select v-model="fireUserId" filterable placeholder="请选择需要通话的人员">
            <el-option v-for="(item,index) in userList" :key="index" :disabled="item.online==0" :value="item.ucId"
                       :label="item.name">
              <span style="float: left">{{ item.name }}</span>
              <span v-if="item.online==0" style="float: right; color: #979797; font-size: 13px">离线</span>
              <span v-else style="float: right; color: #fa1111; font-size: 13px">在线</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button style="align-content: center" type="primary" icon="el-icon-edit" class="filter-item"
                     @click="launchFireVideo">发起视频
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog title="视频展示区域" :visible.sync="videoDialogVisible" width="50%" style="height: 100vh">
      <div style="position: relative">
        <video ref="localVideo" playsinline autoplay width="30%" style="position: absolute;top: 0;left: 0;"></video>
        <video ref="remoteVideo" playsinline autoplay width="100%" style="height: 340px"></video>
      </div>
      <div style="text-align: center;margin-top: 10px">
        <el-button type="danger" @click="hungUp">挂断</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {deleteChannel, launchFireVideo} from "@/api/alirtc";
import 'aliyun-webrtc-sdk'
import {getVideoUser} from "@/api/common";

export default {
  name: "launchVideo",
  data() {
    return {
      videoDialogVisible: false,
      channelId: '',
      userList: [],
      fireUserId: ''
    }
  },
  created() {
    this.$nextTick(() => {
      this.aliWebrtc = new AliRtcEngine();
      this.getVideoUser()
    });
  },
  methods: {
    //获取人员数据信息
    getVideoUser() {
      getVideoUser({}).then(res => {
        this.userList = res.data
      })
    },
    hungUp() {
      this.leaveVideo(true)
    },
    //校验当前设备是否支持
    isSupport(val, debug) {
      let option = {}
      if (debug) {
        option.isDebug = true
      }
      val.isSupport(option).then((res) => {
        this.onJoinEvent(val)
        this.onPublisher(val)
        this.onBye(this.aliWebrtc)
        this.onLeave(val)
        this.OnRefresh(val)
      }).catch((error) => {
        console.log("不支持webrtc", error.message)
      })
    },
    //页面刷新时调用
    OnRefresh(val) {
      window.onbeforeunload = function (e) {
        if (!val) {
          console.log("isSupport失败");
          return;
        }
        val.leaveChannel();
        val.dispose();
      }
    },
    //本地预览
    startPreview(val) {
      this.aliWebrtc.startPreview(this.$refs.localVideo).then(() => {
        console.log("本地预览")
      }).catch((error) => {
        console.log("预览失败", error)
      });
    },
    //推发布流
    publish(val) {
      val.configLocalAudioPublish = true;
      val.configLocalCameraPublish = true;
      val.publish().then(() => {
        console.log("发布流成功")
      }, (error) => {
        console.log("发布流失败", error.message);
      });
    },

    // remote用户加入房间 onJoin
    onJoinEvent(val) {
      val.on("onJoin", (publisher) => {
        console.log(publisher)
        if (publisher.userId) {
          console.log(publisher.userId)
        }
        //重置订阅状态
        //默认订阅远端音频和视频大流，但需要调用subscribe才能生效
        //这里取消默认订阅，根据需求进行订阅
        val.configRemoteAudio(publisher.userId, true);
        val.configRemoteCameraTrack(publisher.userId, true, true);
        // showAlert(publisher.displayName + "加入房间","success");
        // console.log(publisher.displayName + "加入房间");
      });
    },
    //remote流发布事件 onPublish
    onPublisher(val) {
      val.on("onPublisher", (publisher) => {
        val.subscribe(publisher.userId).then((userId) => {
          this.$nextTick(() => {
            val.setDisplayRemoteVideo(userId, this.$refs.remoteVideo, 1)
          });
        }, (error) => {
          console.log(error.message);
        });
      });
    },
    //remote流结束发布事件 onUnPublisher
    onUnPublisher(val) {
      val.on("onUnPublisher", (publisher) => {
        console.log("onUnPublisher", publisher);
      });
    },
    // 被服务器踢出或者频道关闭时回调 onBye
    onBye(val) {
      val.on("onBye", (message) => {
        //1:被服务器踢出
        //2:频道关闭
        //3:同一个ID在其他端登录,被服务器踢出
        var msg;
        switch (message.code) {
          case 1:
            msg = "被服务器踢出";
            break;
          case 2:
            msg = "频道关闭";
            break;
          case 3:
            msg = "同一个ID在其他端登录,被服务器踢出";
            break;
          default:
            msg = "onBye";
        }
        this.$notify.success({
          title: '视频挂断',
          message: msg
        })
        this.leaveVideo(false)
      });
    },
    leaveVideo(val) {
      //结束预览本地摄像头
      this.aliWebrtc.stopPreview();
      //离开频道
      this.aliWebrtc.leaveChannel();
      this.aliWebrtc.dispose();
      this.videoDialogVisible = false
      if (val) {
        deleteChannel({channelId: this.channelId}).then(res => {
        })
      }
    },
    /**
     * 检测到用户离开频道
     * 更新用户列表
     * 移除用户视图
     */
    onLeave(val) {
      val.on("onLeave", (publisher) => {
        console.log(publisher);
        this.leaveVideo(true)
      })
    },
    launchFireVideo() {
      //发起实时视频功能
      //展示弹窗区信息
      let _this = this
      launchFireVideo({fireUserId: _this.fireUserId}).then(res => {
        _this.channelId = res.data.channel
        this.aliWebrtc = new AliRtcEngine();
        this.isSupport(this.aliWebrtc, true)
        this.videoDialogVisible = true
        _this.$nextTick(() => {
          _this.startPreview(_this.aliWebrtc)
          _this.aliWebrtc.joinChannel(res.data, "本地用户").then(obj => {
            _this.publish(_this.aliWebrtc)
            console.log("加入频道成功")
          }).catch((error) => {
            console.log("加入频道失败", error)
          })
        });
      }).catch(error => {
        this.$notify.error({
          title: '加入频道失败',
          message: error.msg
        })
      })
    },

  }
}
</script>

<style scoped>

</style>